package com.jack.netty.udp.client;

import com.jack.netty.log.LoggerManager;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by jack on 15/12/13.
 */
public class UdpClient {

    private int port;
    private String ip;

    public UdpClient(){

    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void sendMessage(String message){
        sendMessage(message,ip,port);
    }

    public void sendMessage(String message,String ip,int port){
        try {
            DatagramSocket socket = new DatagramSocket();
            byte[] bytes = message.getBytes("UTF-8");
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length, InetAddress.getByName(ip),port);
            socket.send(packet);
            socket.close();
        }catch (Exception e){
            LoggerManager.getInstance().getiLogger().error(getClass(),"发送UDP消息失败:"+e.getMessage());
        }
    }
}
